package br.com.mmca.admrespaco.business;

import javax.inject.Inject;

import br.gov.frameworkdemoiselle.annotation.Startup;
import br.gov.frameworkdemoiselle.message.MessageContext;
import br.gov.frameworkdemoiselle.stereotype.BusinessController;
import br.gov.frameworkdemoiselle.template.DelegateCrud;
import br.gov.frameworkdemoiselle.transaction.Transactional;

import br.com.mmca.admrespaco.domain.Condomino;
import br.com.mmca.admrespaco.persistence.CondominoDAO;
import br.com.mmca.admrespaco.message.ErrorMessages;
import br.com.mmca.admrespaco.message.InfoMessages;

@BusinessController
public class CondominoBC extends DelegateCrud<Condomino, Long, CondominoDAO> {
	
	private static final long serialVersionUID = 1L;
	
	@Inject
	private MessageContext msg;
	
	private boolean erro;
	
	@Startup
	@Transactional
	public void load() {
		if (findAll().isEmpty()) {
			insert(new Condomino("Ana Maria", 01,"33445789","ana@mmca.com.br"));
			insert(new Condomino("Cleber", 02,"2148709","cleber@mmca.com.br"));
			insert(new Condomino("Marcelo Junior ", 101,"33445789","marcelo@mmca.com.br"));
			insert(new Condomino("Marcelo Yamashita", 102,"3648754","marceloy@mmca.com.br"));
				}
	}
	
	@Override
	@Transactional
	public void insert(final Condomino se) 
	{
	    validateFields(se);
		if (! erro) 
	    {
		  super.insert(se);
		  msg.add(InfoMessages.condomino_insert_ok, se.getNome());
	    }
		
	}
	
	@Override
	@Transactional
	public void update(final Condomino se) 
	{
		validateFields(se);
		if (! erro) 
		{
		  super.update(se);
	      msg.add(InfoMessages.condomino_update_ok, se.getNome());
	    }
	}
	
	@Override
	@Transactional
	public void delete(final Long id) {
		 super.delete(id);
		 msg.add(InfoMessages.condomino_delete_ok, id);
		 
	}
	
	private void validateFields(final Condomino se) 
	{
		erro=false;
		if(se.getApartamento()== 0)
		  {
			erro=true;
			msg.add(ErrorMessages.condomino_apartamento_nok, se.getApartamento());
			return;
		  }
	}
}
